<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container >
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="发货赤字单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deficitCode">
              <a-input v-model="model.deficitCode" disabled placeholder="请输入发货赤字单号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="审批流程" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="flowFlag">
              <j-dict-select-tag type="list" :disabled="formDisabled" v-model="model.flowFlag" dictCode="deficit_flow_type" placeholder="请选择审批流程" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="customerName">
             <j-popup v-model="model.customerName" :disabled="formDisabled" code="SelectorCustomer" field="customerName" org-fields="name" dest-fields="customerName"></j-popup>
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="业务员" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="salesman">
              <j-select-user-by-dep v-model="model.salesman" :disabled="formDisabled" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="单价类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="priceType">
              <j-dict-select-tag type="list" v-model="model.priceType" :disabled="formDisabled" dictCode="unit_price_type" placeholder="请选择单价类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6" >
            <a-form-model-item label="币种" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="moneyUnit">
              <j-dict-select-tag type="list" v-model="model.moneyUnit" :disabled="formDisabled" dictCode="money_unit" placeholder="请选择币种" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24" style="margin-top:10px;margin-bottom:10px">
            <a-button @click="addGoods" type="primary" :disabled="formDisabled" icon="plus">新增</a-button>
            <erp-category-goods-list-modal
              ref="selectGoodsList"
              :modalWidth="1250"
              :category="1"
              @goodsOk="goodsOk"
              checkval="checkbox"
            >
            </erp-category-goods-list-modal>
                <j-vxe-table
                  keep-source
                  :ref="refKeys[0]"
                  :loading="crmDeficitManagementGoodsTable.loading"
                  :columns="crmDeficitManagementGoodsTable.columns"
                  :dataSource="crmDeficitManagementGoodsTable.dataSource"
                  :maxHeight="300"
                  :disabled="formDisabled"
                  :rowNumber="true"
                  :rowSelection="false"
                  :toolbar="false"
                >
                  <template v-slot:mainQuantity="{ row }">

                    <a-input-number @change="inputQuantity(row)" :disabled="formDisabled" style="width:100%" v-model="row.mainQuantity" />
                  </template>
                  <template v-slot:unitPrice="{ row }">

                    <a-input-number @change="inputQuantity(row)" :disabled="formDisabled" style="width:100%" v-model="row.unitPrice" />
                  </template>
                  <template v-slot:action="{ row }">
                    <a-popconfirm  title="确认删除?" @confirm="() => onDelete(row.goodsId)">
                      <a  href="javascript:;"> 删除 </a>
                    </a-popconfirm>
                  </template>

                </j-vxe-table>

          </a-col>
          <a-col :span="24" >
            <a-form-model-item label="退货原因" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="reason">
              <a-textarea v-model="model.reason" :disabled="formDisabled"  placeholder="请输入退货原因" rows="5"></a-textarea>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
  </a-spin>
</template>

<script>

import {getAction, postAction} from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
import ErpCategoryGoodsListModal from '@comp/base/modal/ErpCategoryGoodsListModal'

  export default {
    name: 'CrmDeficitManagementForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
      ErpCategoryGoodsListModal
    },
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 2 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 22 },
        },
        model:{
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
          flowFlag: [{ required: true, message: '请选择审批流程!' }],
        },
        refKeys: ['crmDeficitManagementGoods', ],
        tableKeys:['crmDeficitManagementGoods', ],
        activeKey: 'crmDeficitManagementGoods',
        // 发货商品赤字管理明细表
        crmDeficitManagementGoodsTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: '物料编码',
              key: 'packageCode',
            },
            {
              title: '物料名称',
              key: 'packageName',
            },
            {
              title: '规格型号',
              key: 'noneSpec',
            },
            {
              title: '主计量单位',
              key: 'meUnit',
              type: JVXETypes.select,
              disabled:true,
              options:[],
              dictCode:"ji_unit",
              placeholder: '请输入${title}',
              defaultValue:'',
            },
            {
              title: '退货数量',
              key: 'mainQuantity',
              type: JVXETypes.slot,
              slotName:'mainQuantity',
            },
            {
              title: '单价',
              key: 'unitPrice',
              type: JVXETypes.slot,
              slotName:'unitPrice',
            },
            {
              title: '金额',
              key: 'amountMoney',
            },
            {
              title: '操作',
              key: 'action',
              type: JVXETypes.slot,
              slotName:'action',
            },
          ]
        },
        url: {
          add: "/deficit/crmDeficitManagement/add",
          edit: "/deficit/crmDeficitManagement/edit",
          queryById: "/deficit/crmDeficitManagement/queryById",
          crmDeficitManagementGoods: {
            list: '/deficit/crmDeficitManagement/queryCrmDeficitManagementGoodsByMainId'
          },
          productByIds: '/review/bussContractRequirementReview/reviewProduct/ids',
        }
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      customFormData: {
        type: Object,
        default: () => {
          return {}
        },
        required: false,
      },
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {

      if (this.customFormData != null && this.customFormData.id) {
        this.model = this.customFormData
        this.editAfter() //现在子表内容需要
      }
    },
    methods: {
      onDelete(key) {
        const dataSource = [...this.crmDeficitManagementGoodsTable.dataSource]
        this.crmDeficitManagementGoodsTable.dataSource = dataSource.filter((item) => item.goodsId !== key)
      },
      inputQuantity(row){
        row.amountMoney=Number(row.mainQuantity*row.unitPrice).toFixed(6)
        row.auxiliaryQuantity =Number(row.mainQuantity*Number(row.coRate)).toFixed(3)
      },
      goodsOk(datas) {

        let _this = this
        postAction(this.url.productByIds, { ids: datas }).then((res) => {
          let erpGoodsList = res.result
          const gids = _this.crmDeficitManagementGoodsTable.dataSource.map((item) => item.goodsId)
            erpGoodsList.forEach(function (item, index) {
              if (gids.indexOf(item.id) > -1) {
                return
              }
              let detail = {}
              detail.mainQuantity = 0
              detail.auxiliaryQuantity = 0
              detail.unitPrice = 0
              detail.amountMoney = 0
              detail.goodsId = item.id
              detail.packageCode = item.code
              detail.packageName = item.name
              detail.noneSpec = item.noneSpec
              detail.coRate = item.coRate
              detail.meUnit = item.meUnit
              detail.auUnit = item.auUnit
              _this.crmDeficitManagementGoodsTable.dataSource.push(detail)
            })
        })
      },
      addGoods: function () {
        // 新增物料
        // console.log(this.$refs.selectGoodsList)
        this.$nextTick(() => {
          this.$refs.selectGoodsList.add()
        })
        // this.$refs.selectGoodsList.add();
        // this.$refs.selectGoodsList.title = "新增";
        // this.$refs.selectGoodsList.disableSubmit = false;
      },

      getCode() {
        postAction('/sys/fillRule/executeRuleByCode/deficit_management_code', {}).then((res) => {
          this.model.deficitCode = res.result
          this.$forceUpdate()
        })
      },
      addBefore(){
        this.getCode()
        Vue.set(this.model, 'flowFlag', 1)
        this.crmDeficitManagementGoodsTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.crmDeficitManagementGoods.list, params, this.crmDeficitManagementGoodsTable)
        }
      },
      //校验所有一对一子表表单
        validateSubForm(allValues){
            return new Promise((resolve,reject)=>{
              Promise.all([
              ]).then(() => {
                resolve(allValues)
              }).catch(e => {
                if (e.error === VALIDATE_FAILED) {
                  // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
                  this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
                } else {
                  console.error(e)
                }
              })
            })
        },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          crmDeficitManagementGoodsList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },

    }
  }
</script>

<style scoped>
</style>